#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试用户提供的代理IP列表
"""

import requests
import concurrent.futures
import time

# 目标测试网站（东财）
TEST_URL = "http://82.push2.eastmoney.com/api/qt/clist/get"
TIMEOUT = 10
MAX_WORKERS = 5  # 并发测试数量

# 用户提供的代理列表（从图片中提取）
PROXY_LIST = [
    "8.212.165.33:3333",           # 菲律宾马尼拉
    "119.3.113.150:9094",          # 上海市
    "116.62.230.32:3128",          # 杭州市
    "118.113.133.135:9999",        # 成都市
    "114.80.37.90:3081",           # 上海市
    "118.178.197.213:3128",        # 杭州市
    "113.45.158.25:3128",          # 未知位置
    "47.109.102.214:6004",         # 成都市
    "101.132.222.120:80",          # 上海市
    "103.158.62.186:8088",         # 孟加拉
    "47.243.92.199:3128",          # 香港
]


def test_proxy(proxy):
    """测试单个代理是否可用"""
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Referer': 'http://quote.eastmoney.com/',
    }
    
    # 格式化代理URL
    if not proxy.startswith('http://') and not proxy.startswith('https://'):
        proxy_url = f"http://{proxy}"
    else:
        proxy_url = proxy
    
    proxies = {
        "http": proxy_url,
        "https": proxy_url
    }
    
    # 测试参数
    params = {"pn": 1, "pz": 10}
    
    start_time = time.time()
    try:
        r = requests.get(
            TEST_URL,
            headers=headers,
            proxies=proxies,
            params=params,
            timeout=TIMEOUT,
            verify=False
        )
        elapsed = time.time() - start_time
        
        if r.status_code == 200:
            # 检查响应是否包含有效数据
            try:
                data = r.json()
                if 'data' in data and 'diff' in data['data']:
                    return True, f"可用 (响应时间: {elapsed:.2f}秒, 状态码: {r.status_code})", elapsed
                else:
                    return False, f"响应异常 (状态码: {r.status_code}, 数据格式错误)", elapsed
            except:
                return False, f"响应异常 (状态码: {r.status_code}, JSON解析失败)", elapsed
        else:
            return False, f"状态码: {r.status_code}", elapsed
    except requests.exceptions.Timeout:
        return False, "连接超时", time.time() - start_time
    except requests.exceptions.ProxyError as e:
        return False, f"代理错误: {str(e)[:60]}", time.time() - start_time
    except requests.exceptions.ConnectionError as e:
        return False, f"连接错误: {str(e)[:60]}", time.time() - start_time
    except Exception as e:
        return False, f"其他错误: {str(e)[:60]}", time.time() - start_time


def test_proxies_batch():
    """批量测试代理"""
    valid_proxies = []
    invalid_proxies = []
    total = len(PROXY_LIST)
    
    print(f"{'='*70}")
    print(f"开始测试 {total} 个代理")
    print(f"目标网站: {TEST_URL}")
    print(f"超时设置: {TIMEOUT} 秒")
    print(f"并发数: {MAX_WORKERS}")
    print(f"{'='*70}\n")
    
    start_time = time.time()
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        future_to_proxy = {executor.submit(test_proxy, proxy): proxy for proxy in PROXY_LIST}
        
        for future in concurrent.futures.as_completed(future_to_proxy):
            proxy = future_to_proxy[future]
            try:
                is_valid, error_msg, elapsed = future.result()
                if is_valid:
                    valid_proxies.append((proxy, elapsed))
                    print(f"✓ [{elapsed:.2f}s] {proxy:<25} - 可用")
                else:
                    invalid_proxies.append((proxy, error_msg))
                    print(f"✗ [{elapsed:.2f}s] {proxy:<25} - 不可用 ({error_msg})")
            except Exception as e:
                invalid_proxies.append((proxy, f"测试异常: {str(e)[:50]}"))
                print(f"✗ [---] {proxy:<25} - 测试异常")
    
    elapsed = time.time() - start_time
    
    # 按响应时间排序
    valid_proxies.sort(key=lambda x: x[1])
    
    print(f"\n{'='*70}")
    print(f"测试完成！")
    print(f"总代理数: {total}")
    print(f"可用代理: {len(valid_proxies)} ({len(valid_proxies)*100//total if total > 0 else 0}%)")
    print(f"不可用代理: {len(invalid_proxies)}")
    print(f"总耗时: {elapsed:.1f} 秒")
    print(f"{'='*70}\n")
    
    if valid_proxies:
        print(f"\n可用的代理列表（按响应速度排序）:")
        print(f"{'='*70}")
        for i, (proxy, elapsed) in enumerate(valid_proxies, 1):
            print(f"  {i:2d}. {proxy:<25} - 响应时间: {elapsed:.2f}秒")
        
        # 生成代理列表（仅IP:PORT格式）
        proxy_list = [proxy for proxy, _ in valid_proxies]
        
        print(f"\n{'='*70}")
        print("可以将以下代理添加到配置文件:")
        print(f"{'='*70}")
        for proxy in proxy_list:
            print(f"  {proxy}")
        
        print(f"\n{'='*70}")
        print("批量添加命令（复制执行）:")
        print(f"{'='*70}")
        print(f"# 方法1: 使用代理配置助手")
        print(f"python dev/代理配置助手.py add {proxy_list[0]}")
        for proxy in proxy_list[1:]:
            print(f"python dev/代理配置助手.py add {proxy}")
        
        print(f"\n# 方法2: 直接写入配置文件")
        print(f"echo '{proxy_list[0]}' > instock/config/proxy.txt")
        for proxy in proxy_list[1:]:
            print(f"echo '{proxy}' >> instock/config/proxy.txt")
        
        # 保存到文件
        try:
            with open('dev/可用代理列表_测试结果.txt', 'w', encoding='utf-8') as f:
                f.write("# 可用代理列表（按响应速度排序）\n")
                f.write(f"# 测试时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"# 测试网站: {TEST_URL}\n\n")
                for proxy in proxy_list:
                    f.write(f"{proxy}\n")
            print(f"\n✓ 已保存可用代理到: dev/可用代理列表_测试结果.txt")
        except Exception as e:
            print(f"\n保存文件失败: {e}")
    else:
        print("\n很遗憾，没有找到可用的代理")
        print("建议:")
        print("  1. 检查网络连接")
        print("  2. 等待一段时间后重试（免费代理可能不稳定）")
        print("  3. 尝试其他代理源")
    
    return valid_proxies, invalid_proxies


if __name__ == "__main__":
    # 禁用SSL警告
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    print("\n" + "="*70)
    print("代理IP测试工具")
    print("="*70 + "\n")
    
    test_proxies_batch()

